// pages/tabbar/schoollist/schoollist.js
const { schoolList, spList, courseList, projectList } = require('../../../config/api/index.js')
const { setStorageSync, getStorageSync, removeStorage, clearStorageSync } = require('../../../utils/wcache.js')
const app = getApp()
let self
Page({
  data: {
		isloading: true,
		filters: [
			{ type: 'school', id: 111, typetext:'考研机构',lists:[]},
			{ type: 'project', id: 112, typetext: '考研科目', lists: [] },
			{ type: 'type', id: 113, typetext: '上课方式', lists: [
				{ id: 1, name:'面授课程'},
				{ id: 2, name: '网络课程' },
				{ id: 3, name: '直播课程' }
			] }
		],
		filterText: '',  // 筛选或者搜索的文本wxRequest
		searchPlaceholder: '请输入培训机构或课程名称',
		menuState: true,  // 菜单状态
		filterType: '',  // 筛选类型
		currfilter: {},  // 当前筛选项
		currPage: 1,
		perPage: 10,  // 每页的数量
		noMoreState: false,  // 没有更多数据
		projectLists: [],  // 科目列表
		schoollists: [],  // 机构列表
		courseLists: [],  // 课程列表
		currPorject:[],  // 当前科目内容
		moreCoursesLoading: false,  // 加载更多课程的状态
		dTime: 3600,  // 本地存储有效时间3600s
  },
  onLoad: function (options) {
		self = this
		wx.showLoading({
			title: '加载中...',
		})
		let currfilter = self.data.currfilter
		currfilter.search = options.search || '',
		self.setData({
			filterText: options.search || '',
			currPorject: options,
			isloading: true,
			currfilter
		})
	
		if (options.type == 'project' || (options.type == 'school')){
			let currfilter = self.data.currfilter
			let key = options.type
			currfilter[key]= options.id
			self.getCourseList(currfilter)
			self.setData({
				currfilter
			})
		} else {
			self.getCourseList(currfilter)
		}
		let deadtime = wx.getStorageSync('ky_porject_deadtime')   // 获取本地存储时间
		if (deadtime){
			if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {  // 本地存储失效
				self.getProjectList()
				self.getSchoolList()
				removeStorage('ky_porject')
				removeStorage('ky_school')
			} else {
				let filters = self.data.filters;
				filters[0].lists = getStorageSync('ky_school');
				filters[1].lists = getStorageSync('ky_porject');
				self.setData({
					filters,
				})
			}
		} else {
			self.getProjectList()
			self.getSchoolList()
		}
		
		
  },
	getProjectList(params) {  // 获取全部科目
		const { currPage, projectLists, dTime } = self.data
		return projectList({
			data: {
				...{ category: 1, per_page: 100 },
				...params
			},
			success(res) {
				let totalPages = res.data.total_pages
				if (currPage <= totalPages) {
					self.setData({
						currPage: currPage + 1,
						projectLists: [...projectLists, ...res.data.items]
					})
					setTimeout(function () {
						self.getProjectList({ page: currPage + 1 })
					}, 0)
				} else {
					let lists = [{ id: '379', name: '一月考研辅导', items: [] }, { id: '380', name: '五月同等学力', items: [] }];
					projectLists.forEach((item) => {
						if (item.pid == '379' || item.pid == '380') {
							lists.forEach((e) => {
								if (e.id == item.pid) {
									e.items.push(item)
								}
							})
						}
					})
					let filters = self.data.filters
					setStorageSync('ky_porject', lists, dTime)  // 保存本地科目列表
					filters[1].lists = lists
					self.setData({
						currPage: 1,
						filters,
					})
				}
			},
			complete(res) {
				self.setData({
					isloading: false
				})
			}
		})
	},
	getSchoolList(params){  // 获取全部机构
		const { currPage, schoollists, dTime } = self.data
		return schoolList({
			data: {
				...{ category: 1 },
				...params
			},
			success(res) {
				let totalPages = res.data.total_pages;
				let totalItems = res.data.total_items
				if (currPage <= totalPages && (parseInt(schoollists.length) + parseInt(res.data.items.length)) < totalItems) {
					self.setData({
						currPage: currPage + 1,
						schoollists: [...schoollists, ...res.data.items]
					})
					setTimeout(function () {
						self.getSchoolList({ page: currPage + 1 })
					}, 0)
				} else {
					let filters = self.data.filters;
					let lists = [...schoollists, ...res.data.items]
					setStorageSync('ky_school', schoollists, dTime)  // 保存本地机构列表
					filters[0].lists = lists
					self.setData({
						schoollists: lists,
						currPage: 1,
						filters,
					})
				}
			},
			complete(res) {
				self.setData({
					isloading: false
				})
			}
		})	
	},
	getCourseList(params, extend){ // 获取课程
		const { perPage, courseLists } = self.data;
		return courseList({
			data:{
				...{ category: 1, per_page: perPage },
				...params
			},
			success(res) {
				let totalPages = res.data.total_pages
				if (extend) {
					let curPage = Math.ceil((courseLists.length + res.data.items.length) / perPage);
					self.setData({
						courseLists: [...courseLists, ...res.data.items],
						curPage,
						noMoreState: parseInt(totalPages) <= curPage
					})
				} else {
					self.setData({
						courseLists: res.data.items,
						curPage: 1,
						noMoreState: parseInt(totalPages) <= Math.ceil(res.data.items.length / perPage)
					})
				}
			},
			complete() {
				self.setData({
					isloading: false,
					moreCoursesLoading: false,
				})
			}
		})
	},
	onmask(e) {
		this.setData({
			maskState: false
		})
	},
	onCurrent(e){
		let currfilter = self.data.currfilter
		let data = e.detail
	
		self.setData({
			currfilter: { ...currfilter, ...data},
			menuState: true,
		})
		wx.pageScrollTo({
			scrollTop: 0,
			duration: 0
		})
		self.getCourseList({ page: self.data.curPage, ...self.data.currfilter })
	},
	onMenuDown(e) {
		self.setData({
			menuState: false,
			filterType: e.detail
		})
		
	},
	bindblur(e) {
		this.setData({
			inputShowed: false,
		})
	},
	showInput() {
		this.setData({
			inputShowed: true
		});
	},
	hideInput() {
		this.setData({
			inputVal: "",
			inputShowed: false
		});
	},
	clearInput() {
		this.setData({
			inputVal: ""
		});
	},
	inputTyping(e) {
		this.setData({
			inputVal: e.detail.value
		});
	},
	searchCourses(e) {
		// 执行搜素
		self.setData({
			listData: [],
			isloading: false
		})
		wx.showLoading({
			title: '加载中...',
			mask: true
		})
		setTimeout(function () {
			wx.hideLoading()
		}, 2000)
		let currfilter = self.data.currfilter
		currfilter.search = e.detail;
		currfilter.project = '';
		currfilter.school = '';
		currfilter.type = '';
		for (let key in currfilter) {
			if (currfilter[key] === '') {
				delete currfilter[key]
			}
		}
		self.setData({
			filterText: e.detail,
			isloading: false,
			currfilter
		})
		self.getCourseList({ page: self.data.curPage, ...currfilter })
	},
	onReachBottom() {
		let currfilter = self.data.currfilter
		for (let key in currfilter) {
			if (currfilter[key] === '') {
				delete currfilter[key]
			}
		}
		if (self.data.noMoreState) {
			return false;
		}
		self.setData({
			moreCoursesLoading: true,
		})
		self.getCourseList({ page: self.data.curPage + 1, ...currfilter }, true)
	},
	showDetail(e) {
		wx.navigateTo({
			url: '/pages/course-detail/course-detail?id=' + e.detail,
		})
	},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})